//
//  HMOAuthViewController.swift
//  sina
//
//  Created by 崔正强 on 17/3/28.
//  Copyright © 2017年 崔正强. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOAuthViewController: UIViewController {

    //自定义根视图
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        //通过webView的代理方法来监控网页加载的状态
        webView.delegate = self
    }
    
    @objc private func close() {
        //执行dismiss
        self.dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func defaultAccount() {
        //执行js
        let jsString = "document.getElementById('userId').value = '15151805604' , document.getElementById('passwd').value = 'pytpytpyt520'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置关闭按钮
        self.view.isOpaque = false
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门", target: self, action: #selector(defaultAccount))
        
        //使用webView加载授权页面
        loadOAuthPage()
    }
    
    //在页面将要消失的时候执行一下dismiss
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //加载授权页面
    private func loadOAuthPage() {
        //1.url 两个必选参数 client_id  redirect_uri
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        
        //2.req
        guard let u = url else {
            return
        }
        let req = URLRequest(url: u)
        
        //3.webView -> req
        webView.loadRequest(req)
        //页面更新的时候,需要提示用户等待 -> SVProgressHUD
//        SVProgressHUD.show()
        
    }
    
}


//在swift中一般用Extension来实现协议方法
extension HMOAuthViewController: UIWebViewDelegate {
    //HUD什么时候转动,什么时候结束
    //实现协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        //开启提示
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //结束提示
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //提示错误
        SVProgressHUD.showError(withStatus: "网页加载错误")
    }
    
    //获取加载页面的url
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.获取加载页面的urlString
        let urlString = request.url?.absoluteString ?? ""

        //2.判断urlString是否包含code
        let flag = "code="
        if urlString.contains(flag) {
            //授权成功
            //3.截取code
            let query = request.url?.query ?? ""
//            print(query)
            let code = query.substring(from: flag.endIndex)
//            print(code)
            //4.通过code请求token -> 请求接口地址
//            loadAccessToken(code: code)
            HMUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (success) in
                if !success {
                    //失败
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
                //成功
                print("登录成功")
                self.dismiss(animated: true, completion: {
                    //发送通知
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: SWITCHROOTVIEWCONTROLLERNOTI), object: nil)
                })
            })
            
            //成功之后就不显示后续的页面
//            return false
        }
//        print(urlString)
        return true
    }
    
    /*以下两个网络请求的方法被封装到视图模型中
    //请求用户授权token
    private func loadAccessToken(code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let para = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "grant_type" : "authorization_code",
                    "code" : code,
                    "redirect_uri" : redirect_uri]
        
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, paramters: para) { (res, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没网")
                return
                
            }
            //已经获取了token --> 通过token获取用户信息
            //发起一个网络请求 -> 获取用户信息
            self.loadUserInfo(res! as! [String : Any])
            
        }
    }
    
    //加载用户信息
    private func loadUserInfo(_  dict: [String : Any]) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]!
        let uid = dict["uid"]!
        
        let para = ["access_token" : token,
                    "uid" : uid]
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, paramters: para) { (res, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没网")
            }
            var userInfoDict = res as! [String : Any]
            //需要将用户信息保存到本地 --> 方便下次使用的时候直接取
            //合并字典 -> 按需存储相关信息
            for (key,value) in dict {
                userInfoDict[key] = value
            }
            //存储用户登录信息 -> 将userInfoDict字典转模型
            let userAccount = HMUserAccount(dict: userInfoDict)
            //对userAccount做归档
            //归档到沙盒
            let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
            print(NSHomeDirectory())
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
            
        }
        
    }
    */
}


